package com.wanwu.channel.server.mock;

import com.alibaba.fastjson.JSONObject;
import com.wanwu.channel.common.exception.SystemException;
import com.wanwu.channel.common.util.IdUtil;
import com.wanwu.channel.common.util.LogUtil;
import com.wanwu.channel.common.util.UtilDate;

import com.wanwu.channel.dao.entity.ChannelPayEntity;
import com.wanwu.channel.dao.inter.ChannelPayDao;
import com.wanwu.channel.dao.inter.ChannelRefundDao;
import com.wanwu.channel.common.util.IdGenerate;
import com.wanwu.channel.remote.alipay.config.ZfbGlobalConfiguration;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@EnableConfigurationProperties(ZfbGlobalConfiguration.class)
@RequestMapping("/alipay")
public class AlipayMockController {

    private static Logger logger = LoggerFactory.getLogger(AlipayMockController.class);

    private static Random random = new Random();

    private static final BigDecimal DIVIDE = new BigDecimal("100");

    @Resource
    private ZfbGlobalConfiguration zfbGlobalConfiguration;

    @Resource
    private ChannelPayDao channelPayDao;

    @Resource
    private ChannelRefundDao channelRefundDao;




    /**
     * 支付宝国际版订单结果查询接口挡板
     *
     * @param
     * @return
     */
    public String mockPayQuery(Map<String, String[]> reqMap) {
        try {
            LogUtil.info(logger, "支付宝国际版订单结果查询mock开始，收到入参{0}", JSONObject.toJSONString(reqMap));
            ChannelPayEntity channelPayEntity = channelPayDao.queryByBizOrderNo(reqMap.get("out_trade_no")[0],"wanlimu_test");
            BigDecimal amount = new BigDecimal(channelPayEntity.getRmbAmount());
            amount = amount.divide(DIVIDE).setScale(2);
            String yuan = String.valueOf(amount);
            String now = UtilDate.getDateTime();
            String sellerId = zfbGlobalConfiguration.getSellerId();
            String tradeNo = IdGenerate.getOrderId() + IdUtil.get12OrderId();
            String str = "<alipay>\n" +
                    "<is_success>T</is_success>\n" +
//                    "<request>\n" +
//                    "<param name=\"_input_charset\">UTF-8</param>\n" +
//                    "<param name=\"service\">single_trade_query</param>\n" +
//                    "<param name=\"partner\">" + zfbGlobalConfiguration.getPid() + "</param>\n" +
//                    "<param name=\"out_trade_no\">" + reqMap.get("out_trade_no")[0] + "</param>\n" +
//                    "<param name=\"sendFormat\">normal</param>\n" +
//                    "</request>\n" +
                    "<response>\n" +
                    "<trade>\n" +
                    "<body>hello</body>\n" +
                    "<buyer_email>intltest059@service.alipay.com</buyer_email>\n" +
                    "<buyer_id>2088122921745555</buyer_id>\n" +
//                    "<discount>0.00</discount>\n" +
//                    "<flag_trade_locked>0</flag_trade_locked>\n" +
//                    "<gmt_create>" + now + "</gmt_create>\n" +
//                    "<gmt_last_modified_time>" + now + "</gmt_last_modified_time>\n" +
                    "<gmt_payment>" + now + "</gmt_payment>\n" +
                    "<is_total_fee_adjust>F</is_total_fee_adjust>\n" +
                    "<operator_role>B</operator_role>\n" +
                    "<out_trade_no>" + reqMap.get("out_trade_no")[0] + "</out_trade_no>\n" +
                    "<payment_type>1</payment_type>\n" +
                    "<total_fee>" + yuan + "</total_fee>\n" +
                    "<quantity>1</quantity>\n" +
                    "<seller_email>test@126.com</seller_email>\n" +
                    "<seller_id>" + sellerId + "</seller_id>\n" +
                    "<subject>world</subject>\n" +
//                    "<to_buyer_fee>0.00</to_buyer_fee>\n" +
//                    "<to_seller_fee>0.02</to_seller_fee>\n" +
//                    "<price>0.02</price>\n" +
                    "<trade_no>" + tradeNo + "</trade_no>\n" +
                    "<trade_status>TRADE_FINISHED</trade_status>\n" +
                    "<use_coupon>F</use_coupon>\n" +
                    "</trade>\n" +
                    "</response>\n" +
                    "<sign></sign>\n" +
                    "<declareSignType>RSA</declareSignType>\n" +
                    "</alipay>";

//            Map<String, String> sPara = new HashMap<>();
//            sPara.put("body", "hello");
//            sPara.put("buyer_email", "intltest059@service.alipay.com");
//            sPara.put("buyer_id", "2088122921745555");
//            sPara.put("gmt_payment", now);
//            sPara.put("is_total_fee_adjust", "F");
//            sPara.put("operator_role", "B");
//            sPara.put("out_trade_no", reqMap.get("out_trade_no")[0]);
//            sPara.put("payment_type", "1");
//            sPara.put("total_fee", yuan);
//            sPara.put("quantity", "1");
//            sPara.put("seller_email", "test@126.com");
//            sPara.put("seller_id", sellerId);
//            sPara.put("subject", "word");
//            sPara.put("trade_no", tradeNo);
//            sPara.put("trade_status", "TRADE_FINISHED");
//            sPara.put("use_coupon", "F");
//            Map<String, String> sPara1 = AlipayCore.paraFilter(sPara);
//            String sign = AlipaySubmit.buildRequestMysign(sPara1, zfbGlobalConfiguration.getSignType(),
//                    zfbGlobalConfiguration.getQudianPublicKey(), zfbGlobalConfiguration.getInputCharset());



            LogUtil.info(logger, "支付宝国际版订单结果查询mock结束，出参{0}", str);
            return str;
        } catch (Exception e) {
            LogUtil.error(logger, e, "支付宝国际版订单结果查询mock失败了");
            throw new SystemException();
        }
    }

    public void mockPayNotify(String outTradeNo,String bizCode) {
        ChannelPayEntity pay = channelPayDao.queryByBizOrderNo(outTradeNo,bizCode);
        Map<String, Object> reqParam = new HashMap<>();
        reqParam.put("notify_time", new Date());
        reqParam.put("notify_type", "trade_status_sync");
        reqParam.put("notify_id", "64ce1b6ab92d00ede0ee56ade98fdf2f4c");
        reqParam.put("sign_type", "RSA");
        reqParam.put("sign", "");
        reqParam.put("out_trade_no", outTradeNo);
        reqParam.put("trade_no", IdGenerate.getOrderId() + IdUtil.get12OrderId() + random.nextInt(100));
        reqParam.put("trade_status", "TRADE_FINISHED");
        BigDecimal amount = new BigDecimal(pay.getRmbAmount());
        amount = amount.divide(DIVIDE).setScale(2);
        reqParam.put("total_fee", amount.toString());
        reqParam.put("currency", pay.getCurrency());
        logger.info("支付宝支付结果回调mock开始，请求参数：{}", JSONObject.toJSONString(reqParam));
        HttpRequest request = HttpRequest.post("http://localhost:8080/alipay/app/pay/notify")
                .bodyText(JSONObject.toJSONString(reqParam));
        HttpResponse response = request.send();
        String responseBody = response.bodyText();
        logger.info("支付宝支付结果回调mock结束，收到应答：{}", responseBody);
    }



    /**
     * 组返回报文xml
     *
     * @param respParam
     * @return
     */
    private String makeResultString(Map<String, String> respParam) {
        JSONObject obj = JSONObject.parseObject(JSONObject.toJSONString(respParam));
//        WechatSignUtil.sign(obj, weixinGlobalConfig.getApiKey());
//        XmlResponse response = changeXmlRoot(obj);
//        return XmlUtil.toXml(response);
        return null;
    }



}
